package com.gsj.service.user.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gsj.dao.user.UserDao;
import com.gsj.domain.user.User;
import com.gsj.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public PageInfo<User> findByPage(String companyId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userDao.findAll(companyId);
        return new PageInfo<>(list);
    }

    @Override
    public void save(User user) {
        user.setId(UUID.randomUUID().toString());

        userDao.save(user);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public User findById(String userId) {
        return userDao.findById(userId);
    }

    @Override
    public Boolean delete(String id) {
        Long userRoleByUserId = userDao.findUserRoleByUserId(id);
        if(userRoleByUserId==0) {
            userDao.delete(id);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 这里是先删除掉用户的角色信息再存入
     * @param userId
     * @param roleIds
     */
    @Override
    public void changeRole(String userId, String[] roleIds) {
       //删除用户的角色
        userDao.deleteUserRoleByUserId(userId);
        //给用户添加角色
        if(roleIds!=null&&roleIds.length>0){
            for (String roleId : roleIds) {
                userDao.saveUserRole(userId,roleId);
            }

        }
    }

    @Override
    public User findByEmail(String email) {
        User user=userDao.findByEmail(email);
        return user;
    }
}
